package zhh.tangbao.auxiliary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import zhh.tangbao.auxiliary.dao.SystemFileDao;
import zhh.tangbao.auxiliary.entity.SystemFile;
import zhh.tangbao.auxiliary.service.SystemFileService;
import zhh.tangbao.auxiliary.vo.SystemFileUploadVo;
import zhh.tangbao.system.config.FileUploadConfig;
import zhh.tangbao.system.exception.ServiceException;
import zhh.tangbao.system.utils.UserHolderUtil;
import zhh.tangbao.user.vo.UserVo;

import java.io.File;
import java.io.IOException;

/**
 * 2023/2/26
 * @author 粥灰灰
 * @version 1.0
 * 系统文件服务
 */

@Slf4j
@Service
public class SystemFileServiceImpl implements SystemFileService {

    @Autowired
    private SystemFileDao systemFileDao;

    @Autowired
    private UserHolderUtil userHolderUtil;


    @Autowired
    private FileUploadConfig fileUploadConfig;


    @Override
    public int bindingFile(String mappingId, Long fileId) {
        return systemFileDao.updateMappingId(fileId, mappingId);
    }

    @Override
    public SystemFile get(Long id) {
        return systemFileDao.selectOne(new QueryWrapper<SystemFile>().eq("id", id));
    }

    @Override
    public String getFileAccessPathById(Long fileId) {
        return systemFileDao.getFileAccessPathById(fileId);
    }

    @Transactional
    @Override
    public SystemFileUploadVo upload(MultipartFile file) {
        try {
            UserVo currentUser = userHolderUtil.getCurrentUser();
            SystemFile add = new SystemFile();
            String fileName = file.getOriginalFilename();
            String type = fileName.substring(fileName.lastIndexOf(".") + 1);
            String saveName = currentUser.getId() + System.currentTimeMillis() + fileName;
            String accessPath = fileUploadConfig.getFileAccessPath(type) + saveName;
            String filePath = fileUploadConfig.getFilePhysicalPath(type) + saveName;
            add.setFileName(saveName)
                    .setFileSize(file.getSize())
                    .setFileAccessPath(accessPath)
                    .setFilePath(filePath)
                    .setBaseCreateInfo(currentUser.getId());
            systemFileDao.insert(add);
            SystemFileUploadVo vo = new SystemFileUploadVo();
            // 往前端传递Long类型数字时可能会发生数据精度异常导致数值不对，所以转换成字符串传递
            vo.setId(String.valueOf(add.getId()));
            vo.setFileAccessPath(accessPath);
            File save = new File(filePath);
            FileUtils.forceMkdirParent(save);
            file.transferTo(save);
            return vo;
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new ServiceException("上传失败");
        }
    }


    @Override
    public boolean canUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return false;
        }
        String name = file.getOriginalFilename();
        int l = name.lastIndexOf(".") + 1;
        // 如果“.”在最后，表示文件名不符合要求
        if (l <= 0 || l >= name.length()) {
            return false;
        }
        // 取后缀并化成小写，通过小写后缀名取得文件对应的大小限制
        return file.getSize() <= fileUploadConfig.getLimitSize(name.substring(l));
    }
}
